package com.js.admin.service.impl;

import com.js.admin.constant.AdminConstant;
import com.js.admin.entity.BaseAppOrder;
import com.js.admin.entity.BaseMenu;
import com.js.admin.entity.BaseTenant;
import com.js.admin.entity.BaseUser;
import com.js.admin.mapper.BaseMenuMapper;
import com.js.admin.mapper.BaseTenantMapper;
import com.js.admin.mapper.BaseUserMapper;
import com.js.admin.service.BaseAppOrderService;
import com.js.admin.service.BaseMenuService;
import com.js.common.exception.auth.ClientTokenException;
import com.js.common.service.impl.BizServiceImpl;
import com.js.common.util.BooleanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ygl
 * @create 2018-10-31
 * @DESCRIPTION
 **/
@Service
public class BaseMenuServiceImpl extends BizServiceImpl<BaseMenu> implements BaseMenuService {

    @Autowired
    private BaseMenuMapper baseMenuMapper;

    @Autowired
    private BaseUserMapper baseUserMapper;

    @Autowired
    private BaseTenantMapper baseTenantMapper;

    @Autowired
    private BaseAppOrderService baseAppOrderService;

    //TODO 此处加缓存
    @Override
    public List<BaseMenu> selectAll() {
        return super.selectAll();
    }

    //TODO 此处加缓存
    /**
     * 获取用户拥有的菜单权限
     * @param userId
     * @param clientId
     * @return
     */
    @Override
    public List<BaseMenu> getUserAuthorityMenuByUserId(String userId, String clientId) {
        BaseUser user = baseUserMapper.selectByPrimaryKey(userId);
        // 管理员获取所有菜单
        if (BooleanUtil.BOOLEAN_TRUE.equals(user.getIsSuperAdmin())) {
            return this.selectAll();
        }

        BaseTenant tenant = baseTenantMapper.selectByPrimaryKey(user.getTenantId());

        // 查询租户是否购买应用
        BaseAppOrder appOrder = baseAppOrderService.selectAppOrder(user.getTenantId(), clientId);

        if (null == appOrder) {
            throw new ClientTokenException("用户未购买应用:" + clientId);
        }

        // 租户管理员获取应用的菜单
        if (tenant.getOwner().equals(userId)) {
            return baseMenuMapper.selectAuthorityMenuByAppId(appOrder.getAppId(), AdminConstant.RESOURCE_TYPE_VIEW);
        }
        // 超级租户的普通操作用户
        else if (BooleanUtil.BOOLEAN_TRUE.equals(tenant.getIsSuperTenant())) {
            return baseMenuMapper.selectAuthorityMenuByUserId(userId, AdminConstant.RESOURCE_TYPE_VIEW);
        }
        // 普通租户的普通用户
        else {
            return baseMenuMapper.selectAuthorityMenuByUserId(userId, AdminConstant.RESOURCE_TYPE_VIEW);
        }
    }
}
